package com.ch.chatbot.domain.proxy;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.*;

public class OpenAIClient {
    public static void main(String[] args) throws Exception {
        String proxyHost = "8.222.196.191"; // 代理服务器地址
        int proxyPort = 8388; // 代理服务器端口
        String targetUrl = "https://api.openai.com/v1/engines/davinci-codex/completions"; // OpenAI API URL

        // 创建代理服务器实例
        Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(proxyHost, proxyPort));

        // 创建URL实例
        URL url = new URL(targetUrl);

        // 打开代理连接
        URLConnection conn = url.openConnection(proxy);

        // 添加代理身份验证
        String password = "DFYqDCFHdmt+WSt3i7EoSQ=="; // 代理服务器密码
        String encryptionMethod = "chacha20-ietf-poly1305"; // 加密方式
        Authenticator.setDefault(new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("", password.toCharArray());
            }
        });
        System.setProperty("socksProxyHost", proxyHost);
        System.setProperty("socksProxyPort", String.valueOf(proxyPort));
        System.setProperty("socksProxyUsername", "");
        System.setProperty("socksProxyPassword", password);
        System.setProperty("socksProxyEncryptionMethod", encryptionMethod);

        // 发送请求
        conn.connect();

        // 读取响应
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            System.out.println(inputLine);
        }
        in.close();
    }
}
